package bb.lanxing.util;

import static com.besall.allbase.bluetooth.service.Protocol.ProtocolConstants.KEY_WATCH_DIAL_ID;
import static com.besall.allbase.bluetooth.service.Protocol.ProtocolConstants.TEST_WATCH_DIAL_OTA;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import com.baidu.mapapi.model.LatLng;
import com.bes.bessdk.BesSdkConstants;
import com.bes.bessdk.utils.ArrayUtil;
import com.bes.bessdk.utils.SPHelper;
import com.bes.sdk.utils.SettingsJsonUtils;
import com.besall.allbase.bluetooth.service.Protocol.ProtocolService;
import com.besall.allbase.common.utils.FileUtils;
import com.besall.allbase.view.activity.chipstoollevel4.protocol.ProtocolPresenter;
import com.github.mikephil.charting.utils.Utils;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Location;
import android.media.ExifInterface;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;
import android.widget.ImageView;

import bb.lanxing.App;
import bb.lanxing.R;
import bb.lanxing.calc.data.SourcePoint;
import bb.lanxing.common.config.Constants;
import bb.lanxing.common.config.UnitConstants;
import bb.lanxing.manager.SharedManager;
import bb.lanxing.model.database.Trackpoint;
import bb.lanxing.service.DownloadService;
import bb.lanxing.util.text.Strings;
import gov.nist.core.Separators;

public class CommonUtil {
    private static final String TAG = "CommonUtil";

    public static final String PACKAGE_INFO = "pkg_info";
    public static final String mCurrentPackageCMD = "pkg_currentPackageCmd";
    public static final String mCurrentPackageIndex = "pkg_currentPackageIndex";
    public static final String mCurrentPackageTotalNum = "pkg_currentPackageTotalNum";
    static final int MAX_FAT32_PATH_LENGTH = 260;
    public static String filePath = "";
    public static String locationPath = "";
    private static String[] specialProvinces = { "北京", "天津", "上海", "重庆", "澳门", "香港" };

    public static int do16BitDiff(int current, int last) {
        return current >= last ? current - last : (current + 0x10000) - last;
    }

    private static boolean isSpecialFat32(char c) {
        switch (c) {
        case ' ', '!', ';', '=', '@', '[', '{', '}', '~', '#', '$', '%', '&', '\'', '(', ')', '+', ',', '-', ']', '^',
                '_', '`' -> {
            return true;
        }
        default -> {
            return false;
        }
        }
    }

    public static String getProcessName(Context context, int pid) {
        List<ActivityManager.RunningAppProcessInfo> runningAppProcesses =
                ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE)).getRunningAppProcesses();
        if (runningAppProcesses == null) {
            return null;
        }
        for (ActivityManager.RunningAppProcessInfo runningAppProcessInfo : runningAppProcesses) {
            if (runningAppProcessInfo.pid == pid) {
                return runningAppProcessInfo.processName;
            }
        }
        return null;
    }

    public static int getProcessIdByName(Context context, String processName) {
        List<ActivityManager.RunningAppProcessInfo> runningAppProcesses =
                ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE)).getRunningAppProcesses();
        if (runningAppProcesses == null) {
            return -1;
        }
        for (ActivityManager.RunningAppProcessInfo runningAppProcessInfo : runningAppProcesses) {
            if (runningAppProcessInfo.processName.equals(processName)) {
                return runningAppProcessInfo.pid;
            }
        }
        return -1;
    }

    public static String getWebHost() {
        int httpDomain = App.getContext().getHttpDomain();
        if (httpDomain != 1) {
            if (httpDomain == 2) {
                return Constants.HOST_TEST;
            }
            if (httpDomain == 3) {
                return Constants.HOST_LOCAL;
            }
            return Constants.HOST_PROD;
        }
        return Constants.HOST_PROD;
    }

    public static String encodeThirtPartyToken(String openId, String accessToken, String name) {
        return Base64.encodeToString((openId + ";" + accessToken + ";" + name).getBytes(), 8);
    }

    public static String decodeThirtPartyOpenId(String datas) {
        StringBuilder sb;
        try {
            try {
                String str = new String(Base64.decode(datas, 8));
                Log.d("decodeThirtPartyOpenId encode = " + str);
                String substring = str.substring(0, str.indexOf(";"));
                Log.d("decodeThirtPartyOpenId openId = " + substring);
                return substring;
            } catch (Exception e) {
                e.printStackTrace();
                sb = new StringBuilder();
                sb.append("decodeThirtPartyOpenId openId = ");
                sb.append((String) null);
                Log.d(sb.toString());
                return null;
            }
        } catch (Throwable unused) {
            sb = new StringBuilder();
            sb.append("decodeThirtPartyOpenId openId = ");
            sb.append((String) null);
            Log.d(sb.toString());
            return null;
        }
    }

    public static String decodeThirtPartyAccessToken(String datas) {
        StringBuilder sb;
        try {
            try {
                String str = new String(Base64.decode(datas, 8));
                Log.d("decodeThirtPartyAccessToken encode = " + str);
                String substring = str.substring(str.indexOf(";") + 1, str.lastIndexOf(";"));
                Log.d("decodeThirtPartyAccessToken accessToken = " + substring);
                return substring;
            } catch (Exception e) {
                e.printStackTrace();
                sb = new StringBuilder();
                sb.append("decodeThirtPartyAccessToken accessToken = ");
                sb.append((String) null);
                Log.d(sb.toString());
                return null;
            }
        } catch (Throwable unused) {
            sb = new StringBuilder();
            sb.append("decodeThirtPartyAccessToken accessToken = ");
            sb.append((String) null);
            Log.d(sb.toString());
            return null;
        }
    }

    public static String decodeThirtPartyName(String datas) {
        try {
            try {
                String str = new String(Base64.decode(datas, 8));
                Log.d("decodeThirtPartyName encode = " + str);
                String substring = str.substring(str.lastIndexOf(";") + 1, str.length());
                Log.d("decodeThirtPartyName name = " + substring);
                return TextUtils.isEmpty(substring) ? "已绑定" : substring;
            } catch (Exception e) {
                e.printStackTrace();
                Log.d("decodeThirtPartyName name = 已绑定");
                TextUtils.isEmpty("已绑定");
                return "已绑定";
            }
        } catch (Throwable unused) {
            Log.d("decodeThirtPartyName name = 已绑定");
            TextUtils.isEmpty("已绑定");
            return "已绑定";
        }
    }

    public static String builderChatUserId(String userId) {
        String sb = new StringBuilder(Base64.encodeToString(Strings.padStart(userId, 8, '0').getBytes(), 8)
                .replaceAll("=", "").replaceAll("\n", "")).reverse().toString();
        Log.d("builderChatUserId userId = " + sb);
        return sb;
    }

    public static String buildAvatarUrl(String userid) {
        return Constants.UPYUN_HOST + "avatar/" + builderChatUserId(userid) + "!avatar";
    }

    public static boolean isPointValid(double lat, double lng) {
        return Math.abs(lat) > 0.1d && Math.abs(lat) < 90.0d && Math.abs(lng) > 0.1d && Math.abs(lng) < 180.0d;
    }

    public static boolean isPointValid(Location location) {
        return isPointValid(location.getLatitude(), location.getLongitude());
    }

    public static boolean isPointValid(Trackpoint trackpoint) {
        return isPointValid(trackpoint.getLatitude(), trackpoint.getLongitude());
    }

    public static boolean isPointValid(SourcePoint sourcePoint) {
        if (sourcePoint == null || !sourcePoint.hasGps()) {
            return false;
        }
        return isPointValid(sourcePoint.getGpsPoint().getLatitude(), sourcePoint.getGpsPoint().getLongitude());
    }

    public static String getMD5(byte[] data) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(data);
            byte[] digest = messageDigest.digest();
            StringBuffer stringBuffer = new StringBuffer("");
            for (int i = 0; i < digest.length; i++) {
                int i2 = digest[i];
                if (i2 < 0) {
                    i2 += 256;
                }
                if (i2 < 16) {
                    stringBuffer.append("0");
                }
                stringBuffer.append(Integer.toHexString(i2));
            }
            return stringBuffer.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getMD5Normal(byte[] data) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(data);
            byte[] digest = messageDigest.digest();
            StringBuffer stringBuffer = new StringBuffer();
            for (byte b : digest) {
                stringBuffer.append(Integer.toString((b & 255) + 256, 16).substring(1));
            }
            return stringBuffer.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getMD5(String str) {
        return getMD5(str.getBytes());
    }

    public static String getMD5(File file) {
        int read;
        int i;
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            byte[] bArr = new byte[4096];
            do {
                read = fileInputStream.read(bArr);
                if (read > 0) {
                    messageDigest.update(bArr, 0, read);
                }
            } while (read != -1);
            fileInputStream.close();
            byte[] digest = messageDigest.digest();
            StringBuilder sb = new StringBuilder("");
            int length = digest.length;
            for (i = 0; i < length; i++) {
                int i2 = digest[i];
                if (i2 < 0) {
                    i2 += 256;
                }
                if (i2 < 16) {
                    sb.append("0");
                }
                sb.append(Integer.toHexString(i2));
            }
            return sb.toString();
        } catch (Exception unused) {
            return "";
        }
    }

    private static String getString(byte[] bArr) {
        StringBuffer stringBuffer = new StringBuffer();
        for (byte b : bArr) {
            stringBuffer.append((int) b);
        }
        return stringBuffer.toString();
    }

    public static byte[] getSha1(String str) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
            messageDigest.update(str.getBytes("UTF-8"));
            return messageDigest.digest();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void setGenderUi(int gender, View backgroundView, ImageView iconView) {
        if (gender == 1) {
            iconView.setImageResource(R.drawable.ic_v1_gender_male);
            backgroundView.setBackgroundResource(R.drawable.ring_3dip_no_side_blue);
            return;
        }
        iconView.setImageResource(R.drawable.ic_v1_gender_female);
        backgroundView.setBackgroundResource(R.drawable.red_round_btn_bg);
    }

    public static void showThread(String className) {
        Thread currentThread = Thread.currentThread();
        Log.d("bici_thread", className + " : " + currentThread.getId() + " , " + currentThread.getName());
    }

    public static boolean isCityCountOne(String provinceName) {
        if (TextUtils.isEmpty(provinceName)) {
            return false;
        }
        int i = 0;
        while (true) {
            String[] strArr = specialProvinces;
            if (i >= strArr.length) {
                return false;
            }
            if (provinceName.contains(strArr[i])) {
                return true;
            }
            i++;
        }
    }

    public static boolean isUserEffective() {
        return SharedManager.getInstance().getUserId() != 0;
    }

    public static List<LatLng> decodePoints(final String encodedPath) {
        int i;
        int i2;
        int length = encodedPath.length();
        ArrayList arrayList = new ArrayList();
        int i3 = 0;
        int i4 = 0;
        int i5 = 0;
        while (i3 < length) {
            int i6 = 1;
            int i7 = 0;
            while (true) {
                i = i3 + 1;
                int charAt = (encodedPath.charAt(i3) - '?') - 1;
                i6 += charAt << i7;
                i7 += 5;
                if (charAt < 31) {
                    break;
                }
                i3 = i;
            }
            int i8 = ((i6 & 1) != 0 ? ~(i6 >> 1) : i6 >> 1) + i4;
            int i9 = 1;
            int i10 = 0;
            while (true) {
                i2 = i + 1;
                int charAt2 = (encodedPath.charAt(i) - '?') - 1;
                i9 += charAt2 << i10;
                i10 += 5;
                if (charAt2 < 31) {
                    break;
                }
                i = i2;
            }
            int i11 = i9 & 1;
            int i12 = i9 >> 1;
            if (i11 != 0) {
                i12 = ~i12;
            }
            i5 += i12;
            arrayList.add(new LatLng(i8 / 100000.0d, i5 / 100000.0d));
            i4 = i8;
            i3 = i2;
        }
        return arrayList;
    }

    public static List<LatLng> parseBaiduPoints(final String strPath) {
        String[] split;
        if (TextUtils.isEmpty(strPath) || (split = strPath.split(";")) == null || split.length <= 0) {
            return null;
        }
        ArrayList arrayList = new ArrayList();
        for (String str : split) {
            String[] split2 = str.split(",");
            if (split2 != null && split2.length == 2) {
                arrayList.add(new LatLng(Double.parseDouble(split2[1]), Double.parseDouble(split2[0])));
            }
        }
        return arrayList;
    }

    public static int getImageDegree(String path) {
        try {
            int attributeInt = new ExifInterface(path)
                    .getAttributeInt(androidx.exifinterface.media.ExifInterface.TAG_ORIENTATION, 0);
            if (attributeInt == 3) {
                return 180;
            }
            if (attributeInt == 6) {
                return 90;
            }
            return attributeInt == 8 ? 270 : 0;
        } catch (Exception unused) {
            Log.w("Image", "can not read exif attributes");
            return 0;
        }
    }

    public static void refreshGallery(Context context, String filePath, String fileName) {
        context.sendBroadcast(
                new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE", Uri.parse("file://" + filePath)));
    }

    public static String getSizeString(long bytes) {
        double d = (bytes / 1024.0d) / 1024.0d;
        if (d < 1.0d) {
            return round(d, 1) + "M";
        }
        return Math.round(d) + "M";
    }

    public static double round(double valueToRound, int numberOfDecimalPlaces) {
        double pow = Math.pow(10.0d, numberOfDecimalPlaces);
        return Math.round(valueToRound * pow) / pow;
    }

    public static String getFormatDistance(double distance) {
        double d2 = ((int) distance) / 1000.0d;
        return d2 < 100.0d ? MessageFormat.format("{0,number,#.##}", d2)
                : (d2 < 100.0d || d2 >= 1000.0d)
                        ? (d2 < 1000.0d || d2 >= 1000000.0d) ? MessageFormat.format("{0,number,#.#w}", d2 / 10000.0d)
                                : MessageFormat.format("{0,number,#}", d2)
                        : MessageFormat.format("{0,number,#.#}", d2);
    }

    public static String getFormatDistancePro(double distance) {
        double d2 = ((int) distance) / 1000.0d;
        return d2 < 100.0d ? MessageFormat.format("{0,number,#.#}", d2)
                : (d2 < 100.0d || d2 >= 1000.0d)
                        ? (d2 < 1000.0d || d2 >= 1000000.0d) ? MessageFormat.format("{0,number,#.#w}", d2 / 10000.0d)
                                : MessageFormat.format("{0,number,#}", d2)
                        : MessageFormat.format("{0,number,#}", d2);
    }

    public static String getKMDistance(double distance) {
        return distance < 1000.0d ? MessageFormat.format("{0,number,#.##}", distance)
                : MessageFormat.format("{0,number,#}", distance);
    }

    public static String getFormatSpeed(double speed) {
        return MessageFormat.format("{0,number,#.##}", speed * 3.6d);
    }

    public static String getFormatCalorie(float vCalorie) {
        return MessageFormat.format("{0,number,#.##}", vCalorie / 1000.0f);
    }

    public static String formatPace(double speed) {
        if (speed == Utils.DOUBLE_EPSILON || Math.abs(speed - Utils.DOUBLE_EPSILON) <= Utils.DOUBLE_EPSILON) {
            return "0'0\"";
        }
        long j = (long) (1000.0d / speed);
        return String.format("%d'%02d\"", Math.min(j / 60, 99L), j % 60);
    }

    public static String formatFriendCount(int count) {
        if (count > 10000) {
            return (count / 10000) + UnitConstants.UNIT_POWER;
        } else if (count > 1000) {
            return (count / 1000) + "k";
        } else {
            if (count < 0) {
                count = 0;
            }
            return String.valueOf(count);
        }
    }

    public static double roundDouble(double value, int scale) {
        double pow = Math.pow(10.0d, scale);
        return Math.round(value * pow) / pow;
    }

    public static double roundDouble(double value, int scale, int roundingMode) {
        return new BigDecimal(value).setScale(scale, roundingMode).doubleValue();
    }

    public static Intent newIntent(Context context, Class<?> cls) {
        return new Intent(context, cls).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    }

    public static synchronized String buildUniqueFileName(File directory, String fileBaseName, String extension) {
        String buildUniqueFileName;
        synchronized (CommonUtil.class) {
            buildUniqueFileName = buildUniqueFileName(directory, fileBaseName, extension, 0);
        }
        return buildUniqueFileName;
    }

    private static String buildUniqueFileName(File directory, String base, String extension, int suffix) {
        String str = "";
        if (suffix > 0) {
            str = "" + Separators.LPAREN + Integer.toString(suffix) + Separators.RPAREN;
        }
        String str2 = str + "." + extension;
        String str3 = truncateFileName(directory, sanitizeFileName(base), str2) + str2;
        return !new File(directory, str3).exists() ? str3 : buildUniqueFileName(directory, base, extension, suffix + 1);
    }

    static String sanitizeFileName(String name) {
        StringBuffer stringBuffer = new StringBuffer(name.length());
        for (int i = 0; i < name.length(); i++) {
            int codePointAt = name.codePointAt(i);
            char charAt = name.charAt(i);
            if (Character.isLetterOrDigit(charAt) || codePointAt > 127 || isSpecialFat32(charAt)) {
                stringBuffer.appendCodePoint(codePointAt);
            } else {
                stringBuffer.append("_");
            }
        }
        return stringBuffer.toString().replaceAll("_+", "_");
    }

    static String truncateFileName(File directory, String name, String suffix) {
        int length = directory.getPath().length() + suffix.length() + 1;
        return name.length() + length > MAX_FAT32_PATH_LENGTH ? name.substring(0, MAX_FAT32_PATH_LENGTH - length)
                : name;
    }

    public static String getJavaEncodingString(String str) {
        return str.replaceAll("\\u0024", "%24").replaceAll("\\u005E", "%5e").replaceAll("\\u007B", "%7b")
                .replaceAll("\\u005B", "%5b").replaceAll("\\u007C", "%7c").replaceAll("\\u002B", "%2b")
                .replaceAll("\\u003F", "%3f").replaceAll("\\u005C", "%5c").replaceAll("`", "%60")
                .replaceAll("\\}", "%7d").replaceAll("\\]", "%5d");
    }

    public static boolean isPackageInstalled(Context context, String packageName) {
        try {
            context.getPackageManager().getPackageInfo(packageName, 1);
            return true;
        } catch (PackageManager.NameNotFoundException unused) {
            return false;
        }
    }

    public static void downloadELPOData(Context context, ProtocolService mProService) {
        String GR3_URL = "";
        String GAL_URL = "";
        String BDS_URL = "";
        SPHelper.putPreference(context, BesSdkConstants.BES_BLE_KEY_ELPO_RUNNING_FLAG, 1);
        //if (Constants.AIROHA_ELPO_GR3_URL.contains("ELPO_GR3_1.DAT")) {
        if (Constants.AIROHA_ELPO_GR3_URL.contains("f1e1G3.pgl")) {
            if (Constants.AIROHA_ELPO_DEBUG) {
                GR3_URL = Constants.AIROHA_ELPO_GR3_URL + "?" + Constants.AIROHA_ELPO_VENDORID_DEBUG + "&"
                        + Constants.AIROHA_ELPO_PROJECTID_DEBUG + "&" + Constants.AIROHA_ELPO_DEVICEID_DEBUG;
            } else {
                GR3_URL = Constants.AIROHA_ELPO_GR3_URL + "?" + Constants.AIROHA_ELPO_VENDORID_RELEASE + "&"
                        + Constants.AIROHA_ELPO_PROJECTID_RELEASE + "&" + Constants.AIROHA_ELPO_DEVICEID_RELEASE;
            }
            String fileNameGR3 = Constants.AIROHA_ELPO_GR3_URL
                    .substring(Constants.AIROHA_ELPO_GR3_URL.lastIndexOf(File.separatorChar) + 1);
            File file = new File(AppFileUtils.buildExternalDirectoryPath("Elpo"), fileNameGR3);
            DownloadService.download(context, mProService, GR3_URL, file.getAbsolutePath());
        }
        //if (Constants.AIROHA_ELPO_GAL_URL.contains("ELPO_GAL_3.DAT")) {
        if (Constants.AIROHA_ELPO_GAL_URL.contains("f1e1E3.pgl")) {
            if (Constants.AIROHA_ELPO_DEBUG) {
                GAL_URL = Constants.AIROHA_ELPO_GAL_URL + "?" + Constants.AIROHA_ELPO_VENDORID_DEBUG + "&"
                        + Constants.AIROHA_ELPO_PROJECTID_DEBUG + "&" + Constants.AIROHA_ELPO_DEVICEID_DEBUG;
            } else {
                GAL_URL = Constants.AIROHA_ELPO_GAL_URL + "?" + Constants.AIROHA_ELPO_VENDORID_RELEASE + "&"
                        + Constants.AIROHA_ELPO_PROJECTID_RELEASE + "&" + Constants.AIROHA_ELPO_DEVICEID_RELEASE;
            }
            String fileNameGAL = Constants.AIROHA_ELPO_GAL_URL
                    .substring(Constants.AIROHA_ELPO_GAL_URL.lastIndexOf(File.separatorChar) + 1);
            File file = new File(AppFileUtils.buildExternalDirectoryPath("Elpo"), fileNameGAL);
            DownloadService.download(context, mProService, GAL_URL, file.getAbsolutePath());
        }
        //if (Constants.AIROHA_ELPO_BDS_URL.contains("ELPO_BDS_3.DAT")) {
        if (Constants.AIROHA_ELPO_BDS_URL.contains("f1e1C3.pgl")) {
            if (Constants.AIROHA_ELPO_DEBUG) {
                BDS_URL = Constants.AIROHA_ELPO_BDS_URL + "?" + Constants.AIROHA_ELPO_VENDORID_DEBUG + "&"
                        + Constants.AIROHA_ELPO_PROJECTID_DEBUG + "&" + Constants.AIROHA_ELPO_DEVICEID_DEBUG;
            } else {
                BDS_URL = Constants.AIROHA_ELPO_BDS_URL + "?" + Constants.AIROHA_ELPO_VENDORID_RELEASE + "&"
                        + Constants.AIROHA_ELPO_PROJECTID_RELEASE + "&" + Constants.AIROHA_ELPO_DEVICEID_RELEASE;
            }
            String fileNameBDS = Constants.AIROHA_ELPO_BDS_URL
                    .substring(Constants.AIROHA_ELPO_BDS_URL.lastIndexOf(File.separatorChar) + 1);
            File file = new File(AppFileUtils.buildExternalDirectoryPath("Elpo"), fileNameBDS);
            DownloadService.download(context, mProService, BDS_URL, file.getAbsolutePath());
        }
    }

    public static String wifiOtaToJson() throws JSONException {
        Calendar calendar = Calendar.getInstance();
        JSONObject json = new JSONObject();
        json.put("year", calendar.get(Calendar.YEAR));
        json.put("month", calendar.get(Calendar.MONTH) + 1);
        json.put("day", calendar.get(Calendar.DATE));
        json.put("hour", calendar.get(Calendar.HOUR_OF_DAY));
        json.put("minute", calendar.get(Calendar.MINUTE));
        json.put("second", calendar.get(Calendar.SECOND));
        json.put("millisecond", calendar.get(Calendar.MILLISECOND));
        return json.toString();
    }

    public static void saveBBServiceDownloadWifiOTAInfo(Context context) {
        try {
            String jsonOutput = wifiOtaToJson();
            Log.d("jsonOutput:::" + jsonOutput);
            File old_file = new File(filePath);
            if (old_file.exists()) {
                boolean del = old_file.delete();
            }
            File file = new File(AppFileUtils.buildExternalDirectoryPath("WIFI_OTA"), SettingsJsonUtils.WIFI_OTA_JSON);
            RandomAccessFile raf = new RandomAccessFile(file, "rwd");
            raf.seek(file.length());
            raf.write(jsonOutput.getBytes());
            raf.close();
            filePath = file.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String locationToJson(LatLng location) throws JSONException {
        JSONObject json = new JSONObject();
        json.put("lat", location.latitude);
        json.put("lon", location.longitude);
        json.put("alt", 0);
        return json.toString();
    }

    public static void saveLocationData(LatLng location,File file) {
        try {
            if (location != null) {
                Log.d("onPointChanged: latitude " + location.latitude + ", longitude " + location.longitude);
            }
            String jsonOutput = locationToJson(location);
            Log.d("jsonOutput:::" + jsonOutput);
            RandomAccessFile raf = new RandomAccessFile(file, "rwd");
            raf.seek(file.length());
            raf.write(jsonOutput.getBytes());
            raf.close();
            locationPath = file.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String transFileToJson(String cmdCode, String successFlag) throws JSONException {
        JSONObject json = new JSONObject();
        json.put("cmdCode", cmdCode);
        json.put("successFlag", successFlag);
        return json.toString();
    }

    public static void saveTransFileRecordData(Context context, String cmdCode, String successFlag) {
        try {
            String jsonOutput = transFileToJson(cmdCode, successFlag);
            Log.d("jsonOutput:::" + jsonOutput);
            File file = new File(AppFileUtils.buildExternalDirectoryPath("TransRecord"), "transRecord.json");
            RandomAccessFile raf = new RandomAccessFile(file, "rwd");
            raf.seek(file.length());
            raf.write(jsonOutput.getBytes());
            raf.close();
            filePath = file.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static boolean saveDeviceProfile(String saveString, String modelName, String sn) {
        if (modelName == null || sn == null) {
            android.util.Log.d(TAG, " modelName or sn is null,return false ");
            return false;
        }
        android.util.Log.i(TAG, "saveDeviceProfile saveString = " + saveString);
        String settingsDir = FileUtils.checkExternalDirectoryPathExist(false, modelName, sn, SettingsJsonUtils.SETTINGS);
        if (settingsDir == null) {
            bb.lanxing.util.Log.d(TAG, " the  settings dir is null,return false "); // SettingsJsonUtils.ROUTE_BOOKS_JSON
            return false;
        }

        File profileFile = new File(settingsDir, SettingsJsonUtils.PANEL_JSON);
        try {
            if (!profileFile.exists() && !profileFile.createNewFile()) {
                throw new IllegalStateException("cannot create profile file !");
            }
            BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(profileFile, false));
            bufferedWriter.write(saveString, 0, saveString.length());
            bufferedWriter.flush();
            bufferedWriter.close();
            return true;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void sendPanelsJsonFile(Context context, String modelName, String sn) {
        String extraPath = com.besall.allbase.common.utils.FileUtils.checkExternalDirectoryPathExist(true, modelName,
                sn, SettingsJsonUtils.SETTINGS, SettingsJsonUtils.PANEL_JSON);
        android.util.Log.i("CommonUtil", "sendPanelsJsonFile PATH: " + extraPath);
        String fileName = extraPath.substring(extraPath.lastIndexOf(File.separatorChar) + 1);
        android.util.Log.i("CommonUtil", "fileName: " + fileName);
        byte[] pathPanels = ArrayUtil.toBytes(ArrayUtil.str2HexStr(extraPath));
        if (extraPath.contains(SettingsJsonUtils.PANEL_JSON)) {
            SPHelper.putPreference(context, KEY_WATCH_DIAL_ID, fileName);
            android.util.Log.i("CommonUtil", "sendDeveloperData: " + fileName);
            ProtocolPresenter.getInstance().sendDeveloperData(TEST_WATCH_DIAL_OTA, pathPanels);
        }
    }

    public static void saveCurrentPackageCMD(Context context, String currentPackageCMD) {
        if (context == null) {
            return;
        }
        android.util.Log.i("CommonUtil", "saveCurrentPackageCMD: " + currentPackageCMD);
        SharedPreferences deviceInfoPrefernce = context.getSharedPreferences(PACKAGE_INFO, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = deviceInfoPrefernce.edit();
        editor.putString(mCurrentPackageCMD, currentPackageCMD);
        editor.commit();
    }

    public static String getCurrentPackageCMD(Context context) {
        if (context == null) {
            return "00";
        }
        String pkg_currentPackageCMD;
        SharedPreferences deviceInfoPrefernce = context.getSharedPreferences(PACKAGE_INFO, Context.MODE_PRIVATE);
        pkg_currentPackageCMD = deviceInfoPrefernce.getString(mCurrentPackageCMD, "00");
        android.util.Log.i("CommonUtil", "pkg_currentPackageCMD: " + pkg_currentPackageCMD);
        return pkg_currentPackageCMD;
    }

    public static void saveCurrentPackageIndex(Context context, int currentPackageIndex) {
        if (context == null) {
            return;
        }
        android.util.Log.i("CommonUtil", "currentPackageIndex: " + currentPackageIndex);
        SharedPreferences deviceInfoPrefernce = context.getSharedPreferences(PACKAGE_INFO, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = deviceInfoPrefernce.edit();
        editor.putInt(mCurrentPackageIndex, currentPackageIndex);
        editor.commit();
    }

    public static int getCurrentPackageIndex(Context context) {
        if (context == null) {
            return 0;
        }
        int pkg_currentPackageIndex = 0;
        SharedPreferences deviceInfoPrefernce = context.getSharedPreferences(PACKAGE_INFO, Context.MODE_PRIVATE);
        pkg_currentPackageIndex = deviceInfoPrefernce.getInt(mCurrentPackageIndex, 0);
        android.util.Log.i("CommonUtil", "pkg_currentPackageIndex: " + pkg_currentPackageIndex);
        return pkg_currentPackageIndex;
    }

    public static void saveCurrentPackageTotalNum(Context context, int currentPackageTotalNum) {
        if (context == null) {
            return;
        }
        SharedPreferences deviceInfoPrefernce = context.getSharedPreferences(PACKAGE_INFO, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = deviceInfoPrefernce.edit();
        editor.putInt(mCurrentPackageTotalNum, currentPackageTotalNum);
        editor.commit();
    }

    public static int getCurrentPackageTotalNum(Context context) {
        if (context == null) {
            return 0;
        }
        int pkg_currentPackageTotalNum = 0;
        SharedPreferences deviceInfoPrefernce = context.getSharedPreferences(PACKAGE_INFO, Context.MODE_PRIVATE);
        pkg_currentPackageTotalNum = deviceInfoPrefernce.getInt(mCurrentPackageTotalNum, 0);
        return pkg_currentPackageTotalNum;
    }
}
